const { resolve } = require('path');

const jp = ({ url, params, cbName }) => {
  const generateURL = () => {
    let dataSrc = '';
    for (const key in params) {
      if (Object.prototype.hasOwnProperty.call(params, key)) {
        const element = object[key];
        dataSrc += `${key}=${element}&`;
      }
    }
    dataSrc += `callback=${cbName}`;
    return `${url}?${dataSrc}`;
  };

  return new Promise((resolve, reject) => {
    let scriptElm = document.createElement('script');
    scriptElm.src = generateURL();
    document.body.appendChild(scriptElm);
    window[cbName] = (data) => {
      resolve(data);
      document.removeChild(scriptElm);
    };
  });
};

const jp1 = ({ url, params, cbName }) => {
  const generateURL = () => {
    let src = '';
    for (key in params) {
      if (params.hasOwnProperty(key)) {
        src += `${key}=${params[key]}&`;
      }
    }
    return `${url}?${src}cb=${cbName}`;
  };

  return new Promise((resolve, reject) => {
    let scriptElm = Document.createElement('script');
    scriptElm.src = generateURL();
    document.body.appendChild(scriptElm);

    window[cbName] = (data) => {
      resolve(data);
      document.removeChild(scriptElm);
    };
  });
};

const jp2 = ({ url, params, cbName }) => {
  const generateURL = () => {
    let src = '';
    for (key in params) {
      if (params.hasOwnProperty(key)) {
        src += `${key}=${params[key]}&`;
      }
    }
    return `${url}?${src}callback=${cbName}`;
  };

  return new Promise((resolve, reject) => {
    let scriptElm = document.createElement('script');
    scriptElm.src = generateURL();
    document.body.appendChild(scriptElm);

    window[cbName] = (data) => {
      resolve(data);
      document.removeChild(scriptElm);
    };
  });
};

const jp4 = ({ url, params, cbName }) => {
  const generateURL = () => {
    let src = '';
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        src += `${key}=${params[key]}&`;
      }
    }
    return `${url}?${src}callback=${cbName}`;
  };

  return new Promise((resolve, reject) => {
    let scriptElm = document.createElement('script');
    scriptElm.src = generateURL();
    document.body.appendChild(scriptElm);

    window[cbName] = (data) => {
      resolve(data);
      document.removeChild(scriptElm);
    };
  });
};

const jp5 = ({ url, params, cbName }) => {
  const generateURL = () => {
    let src = '';
    for (let key of Object.keys(params)) {
      src += `${key}=${params[key]}&`;
    }

    return `${url}?${src}callback=${cbName}`;
  };

  return new Promise((resolve, reject) => {
    const scriptElm = document.createElement('script');
    scriptElm.src = generateURL();
    document.body.appendChild(scriptElm);

    window[cbName] = (data) => {
      resolve(data);
      document.body.removeChild(scriptElm);
    };
  });
};
